package com.vx.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.vx.ratingTool.Player;
import com.vx.ratingTool.bo.PlayerBOimpl;
import com.vx.ratingTool.dao.PlayerDAOimpl;
import com.vx.ratingTool.match.Match;
import com.vx.ratingTool.match.MatchFinder;

@Controller
@RequestMapping("/simulateNMatches")
public class SimulateNMatchesController {

	private PlayerDAOimpl playerDAO;
	private PlayerBOimpl playerBO;

	public PlayerDAOimpl getPlayerDAOimpl() {
		return playerDAO;
	}

	@Autowired
	public void setPlayerDAOimpl(PlayerDAOimpl playerDAO) {
		this.playerDAO = playerDAO;
	}

	public PlayerBOimpl getPlayerBO() {
		return playerBO;
	}

	@Autowired
	public void setPlayerBO(PlayerBOimpl playerBO) {
		this.playerBO = playerBO;
	}

	private List<Player> players;

	@RequestMapping(method = RequestMethod.GET)
	public void setupForm() {
	}

	@RequestMapping(method = RequestMethod.POST)
	public String sumbitForm(@RequestParam("count") int count, Model model) {
		Random rnd = new Random();
		List<Player> dataBaseList = playerBO.GetListOfPlayers();
		List<Player> playerPoolList;
		MatchFinder MF;
		Match M;

		for (int i = 0; i < count; i++) {

			playerPoolList = new ArrayList<Player>();
			for (int j = 0; j < 200; j++) {
				playerPoolList.add(dataBaseList.get(rnd.nextInt(dataBaseList.size())));
			}

			Player newPlayer = playerBO.findById(rnd.nextInt(playerBO.GetListOfPlayers().size()));
			playerPoolList.add(newPlayer);

			MF = new MatchFinder(playerPoolList, newPlayer, 50, 50);
			M = MF.findMatch();
			M.Simulate();

			List<Player> updList = new ArrayList<Player>(M.getTeamA());
			playerBO.massUpdate(updList);
			updList = new ArrayList<Player>(M.getTeamB());
			playerBO.massUpdate(updList);
		}

		String success = "Success";
		model.addAttribute("success", success);
		return "simulateNMatches";
	}
}